// packageH/chitchat/chatList/chatList.js
const app = getApp();

let loopGetChatDataHandle = null;
let isLoopGetChatData = false;
let loopGetChatDataCount = 0;
let loopGetingChatData = false;
let socketInstance = null;
let websocketRequestUrl = null;
let websocketConfig = {};
let websocketReconnetCount = 0;
let websocketReconnectTimer = null;
let websocketMaxReconnetCount = 10;
let websocketConntectCheckTimer = null;
// let networkOffline = false;
// function arrayToObject(arr, arrValueKey) {
//   let obj = {};
//   for (let index = 0; index < arr.length; index++) {
//     const element = arr[index];
//     obj[element[arrValueKey]] = element;
//   }
//   return obj;
// }
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    chatList: [],
    employeeChatList: [],
    listSetting: {},

    isEmployee: false,

    chatListPagination: {
      pages: 1,
      finished: false,
      loading: false
    },
    employeeChatPagination: {
      pages: 1,
      finished: false,
      loading: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

    await this.getSetting();
    this.getWebscoketConfig();
    this.getEmployeeChatData();
    await this.getChatData();
    this.loopGetChatData();
    wx.onNetworkStatusChange((res) => {
      console.log("onNetworkStatusChange", res.isConnected);
      console.log("onNetworkStatusChange", res.networkType);
    });
  },

  swichTabTItem(evt) {
    this.setData({
      activeTab: evt.detail.index
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  del_record(data){
    let id = data.detail.id;
    let urlStr = app.getNetAddresss('plugin.yun-chat.frontend.h5.chat.delete');
    app._postNetWork({
      url:urlStr,
      data:{queue_id:id},
      success:async (resdata)=>{
        let {msg,result} = resdata.data;
        if(result == 0){
          return app.tips(msg)
        }
        if(this.data.chatList && this.data.chatList.length!==0){
          this.data.chatList = this.data.chatList.filter(item => {
            return item.id !== data.id;
        })
          this.setData({chatList:this.data.chatList})
        }
        if(this.data.employeeChatList && this.data.employeeChatList.length!==0){
          this.data.employeeChatList = this.data.employeeChatList.filter(item => {
            return item.id !== data.id;
          })
          this.setData({employeeChatList:this.data.employeeChatList})
        }
      }
    })
  },
  getWebscoketConfig() {
    if (!this.data.isEmployee) {
      return;
    }
    let urlStr = app.getNetAddresss('plugin.yun-chat.frontend.chat.get-ws-setting');
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return app.tips(res.msg);
        websocketConfig = res.data.wss_params;
        websocketRequestUrl = `${websocketConfig.host}?appId=${websocketConfig.appId}&signature=${websocketConfig.signature}&nonceStr=${websocketConfig.nonceStr}&timestamp=${websocketConfig.timestamp}&clientid=${websocketConfig.clientid}&agent_id=${websocketConfig.agent_id}`;
        this.socketInit();
      }
    });

  },
  getSetting() {
    return new Promise((resolve, reject) => {
      let urlStr = app.getNetAddresss('plugin.yun-chat.frontend.h5.chat.get-list-setting');
      app._postNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result !== 1) return app.tips(res.msg);
          if (res.data.employee_id > 0) {
            this.setData({
              isEmployee: true
            });
          }
          resolve();
        }
      });
    });


  },

  socketInit() {
    console.log("执行socket链接", websocketRequestUrl);
    if (socketInstance === null) {
      socketInstance = wx.connectSocket({
        url: websocketRequestUrl
      });
      socketInstance.onMessage(response => {
        let chatNewData = JSON.parse(response.data);
        console.log(chatNewData);
        if (chatNewData.uid) {
          let mIndex = 0;
          let employeeChatList = this.data.employeeChatList;
          let chat = employeeChatList.find((item, index) => {
            if (item.uid == chatNewData.uid) {
              mIndex = index;
              return item;
            }
          });
          console.log(mIndex, chat);
          if (chat) {
            switch (chatNewData["content_type"]) {
            case 0:
              chat["last_chat_content"] = chatNewData["data"];
              break;
            case 1:
              chat["last_chat_content"] = "[图片]";
              break;
            case 2:
              chat["last_chat_content"] = "[商品]";
              break;
            case 3:
              chat["last_chat_content"] = "[订单]";
              break;
            }
            chat["un_read_num"]++;
            chat["updated_at"] = chatNewData["time"];
            employeeChatList.splice(mIndex, 1);
            employeeChatList.unshift(chat);
            this.setData({
              employeeChatList
            });
          } else {
            employeeChatList.unshift(chatNewData);
            this.setData({
              employeeChatList
            });
          }
        }
      });
      socketInstance.onError(error => {
        socketInstance.close();
        this.socketReconnet();
        socketInstance = null;
      });
      socketInstance.onOpen(() => {
        this.checkSocketConnectState();
      });
      socketInstance.onClose(() => {
        clearInterval(websocketConntectCheckTimer);
        websocketConntectCheckTimer = null;
      });
    }
  },

  checkSocketConnectState() {
    if (websocketConntectCheckTimer !== null) {
      return;
    }
    websocketConntectCheckTimer = setInterval(() => {
      if (socketInstance) {
        if (socketInstance.readyState == 1) {
          console.log(JSON.stringify({
            type: "ping"
          }));
          socketInstance.send({
            data: JSON.stringify({
              type: "ping"
            })
          });
          websocketReconnetCount = 0;
        } else {
          clearInterval(websocketConntectCheckTimer);
          websocketConntectCheckTimer = null;
          socketInstance.close();
          this.socketReconnet();
        }
      } else {
        clearInterval(websocketConntectCheckTimer);
        websocketConntectCheckTimer = null;
      }
    }, 5000);
  },

  socketReconnet() {
    if (websocketReconnectTimer !== null) {
      return;
    }
    websocketReconnectTimer = setInterval(() => {
      websocketReconnetCount++;
      this.socketInit();
      if (websocketReconnetCount >= websocketMaxReconnetCount) {
        clearInterval(websocketReconnectTimer);
        websocketReconnectTimer = null;
        //    VanNotify("网路连接不可用");
      }
    }, 5000);
  },

  getChatData() {
    return new Promise((resolve, reject) => {
      if (!isLoopGetChatData) {
        if (this.data.chatListPagination.finished || this.data.chatListPagination.loading) {
          return;
        }
      }
      let pages = this.data.chatListPagination.pages;
      if (isLoopGetChatData) {
        pages = 1;
      } else {
        this.data.chatListPagination.loading = true;
      }
      let urlStr = app.getNetAddresss('plugin.yun-chat.frontend.h5.chat.get-list');
      app._postNetWork({
        url: urlStr,
        data: {
          page: pages
        },
        success: (resdata) => {
          let res = resdata.data;
          let {
            data: {
              data,
              per_page,
              current_page,
              last_page
            },
            msg,
            result
          } = res;
          this.data.chatListPagination.loading = false;
          if (result !== 1) return app.tips(msg);
          let chatList;
          if (pages == 1) {
            chatList = data;
          } else {
            chatList = this.data.chatList.concat(data);
          }
          this.setData({
            chatList
          });

          // for (const key in data) {
          //   if (Object.hasOwnProperty.call(data, key)) {
          //     const element = data[key];
          //     let uid = element["has_one_employee"]["uid"];
          //     let target = "chatList."+uid;
          //     this.setData({
          //       [target]:element
          //     });
          //   }
          // }
          if (isLoopGetChatData) {
            isLoopGetChatData = false;
            loopGetingChatData = false;
            this.data.chatListPagination.pages = 1;
          } else {
            if (data.length < per_page || current_page == last_page) {
              this.data.chatListPagination.finished = true;
            }
            this.data.chatListPagination.pages++;
          }
          resolve();
        }
      });
    });

  },

  loopGetChatData() {
    clearInterval(loopGetChatDataHandle);
    loopGetChatDataHandle = null;
    loopGetChatDataCount = 0;
    if (loopGetChatDataHandle === null) {
      loopGetChatDataHandle = setInterval(() => {
        console.log(loopGetChatDataCount);
        if (loopGetingChatData === false) {
          isLoopGetChatData = true;
          if (this.data.isEmployee == true) {
            if (this.data.activeTab == 0) {
              this.getEmployeeChatData();
            } else {
              this.getChatData();
            }
          } else {
            this.getChatData();
          }
          loopGetChatDataCount++;
          if (loopGetChatDataCount >= 100) {
            clearInterval(loopGetChatDataHandle);
            loopGetChatDataHandle = null;
          }
        }
      }, 5000);
    } else {
      loopGetChatDataCount = 0;
    }
  },

  getEmployeeChatData() {
    if (!isLoopGetChatData) {
      if (this.data.isEmployee === false || this.data.employeeChatPagination.finished || this.data.employeeChatPagination.loading) {
        return;
      }
    }
    let pages = this.data.employeeChatPagination.pages;
    if (isLoopGetChatData) {
      pages = 1;
    } else {
      this.data.employeeChatPagination.loading = true;
    }
    let urlStr = app.getNetAddresss('plugin.yun-chat.frontend.chat.get-list');
    app._postNetWork({
      url: urlStr,
      data: {
        page: pages
      },
      success: (resdata) => {
        let res = resdata.data;
        let {
          data: {
            data,
            per_page,
            current_page,
            last_page
          }
        } = res;
        this.data.employeeChatPagination.loading = false;
        if (res.result !== 1) return app.tips(res.msg);

        if (data.length < per_page || current_page == last_page) {
          this.data.employeeChatPagination.finished = true;
        }
        let employeeChatList;
        if (pages == 1) {
          employeeChatList = data;
        } else {
          employeeChatList = this.data.employeeChatList.concat(data);
        }

        this.setData({
          employeeChatList
        });
        //data = arrayToObject(data, "uid");
        // for (const key in data) {
        //   if (Object.hasOwnProperty.call(data, key)) {
        //     const element = data[key];
        //     let uid = element["uid"];
        //     let target = "employeeChatList."+uid;
        //     this.setData({
        //       [target]:element
        //     });
        //   }
        // }
        if (isLoopGetChatData) {
          isLoopGetChatData = false;
          loopGetingChatData = false;
          this.data.employeeChatPagination.pages = 1;
        } else {
          if (data.length < per_page || current_page == last_page) {
            this.data.employeeChatPagination.finished = true;
          }
          this.data.employeeChatPagination.pages++;
        }
      }
    });
  },


  toEmployeeChat(evt) {
    let item = evt.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageH/chitchat/chatWindow/chatWindow?chatType=2&user_id=' + item.uid,
    });
  },

  enterChatPage(evt) {
    let item = evt.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageH/chitchat/chatWindow/chatWindow?chatType=1&groupId=' + item.group_id + "&employeeId=" + item.employee_id,
    });
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let chatListPagination = {
      pages: 1,
      finished: false,
      loading: false
    };
    let employeeChatPagination = {
      pages: 1,
      finished: false,
      loading: false
    };
    this.setData({
      chatListPagination,
      employeeChatPagination
    });
    this.getEmployeeChatData();
    await this.getChatData();
    this.loopGetChatData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(loopGetChatDataHandle);
    loopGetChatDataHandle = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (socketInstance) {
      socketInstance.close();
    }
    clearInterval(loopGetChatDataHandle);
    loopGetChatDataHandle = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isEmployee == true) {
      if (this.data.activeTab == 0) {
        this.getEmployeeChatData();
      } else {
        this.getChatData();
      }
    } else {
      this.getChatData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});